package dproxy

import (
	"gitee.com/yysf-xin/dproxy/controller"
	"gitee.com/yysf-xin/dproxy/pkg/app"
	"gitee.com/yysf-xin/dproxy/pkg/svr"
	"gitee.com/yysf-xin/dproxy/pkg/tools"
	"github.com/soheilhy/cmux"
	"net/http"
)

type Server struct {
	Conf     *app.Config
	services *app.Services
	Proxy    *svr.Proxy
	Route    *controller.RouterConfig
	CMux     cmux.CMux
	Web      *http.Server `wire:"-"`
}

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.URL.Host == "" {
		if s.Conf.File.EnableWeb {
			//if r.URL.Path == "/" {
			//	http.Redirect(w, r, app.CtxPath, http.StatusFound)
			//	return
			//}
			s.Route.Server.ServeHTTP(w, r)
			return
		}
	} else if s.Conf.File.EnableProxy && s.Proxy != nil {
		s.Proxy.ServeHTTP(w, r)
		return
	}
	http.NotFound(w, r)
}

func (s *Server) ListenAndServe() (err error) {
	s.Route.Init()
	s.Web = &http.Server{
		Handler: s,
		Addr:    s.Conf.File.Addr,
	}
	if err != nil {
		tools.Log.Println("start web err", err)
	} else {
		tools.Log.Println("start web at", s.Conf.File.Addr)
	}
	l := s.CMux.Match(cmux.Any())
	go s.Web.Serve(l)

	err = s.CMux.Serve()
	return
}
